import React, { useRef, useEffect } from "react";
import { Form, Input, Button, Select } from "antd";
import "./index.less";

const { Option } = Select;
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 }
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 }
};

function AddFrom(props) {
  const formRef = useRef({
    name: '',
    parentType: '0'
  });

  const onFinish = values => {
    props.onOk(values);
    formRef.current.resetFields();
  };

  const onCancel = () => {
    props.onCancel();
    formRef.current.resetFields();
  };

  useEffect(() => {
    formRef.current.setFieldsValue({
      name: props.name,
    });
  })

  return (
    <Form
      {...layout}
      ref={formRef}
      name='control-hooks'
      onFinish={onFinish}
      initialValues={{
        name: '',
        parentType: '0'
      }}
    >
      <Form.Item
        name='parentType'
        label='所属分类'
        rules={[{ required: true }]}
      >
        <Select
          placeholder='请选择所属分类'
          allowClear
        >
          <Option value='0'>一级分类</Option>
        </Select>
      </Form.Item>
      <Form.Item
        name='name'
        label='分类名称'
        rules={[
          { required: true, whitespace: true, message: "请输入分类名称!" },
          { min: 2, message: "名称至少2位" },
          { max: 12, message: "名称最多12位" }
        ]}
      >
        <Input placeholder='请请入分类名称' />
      </Form.Item>
      <Form.Item {...tailLayout}>
        <Button type='primary' htmlType='submit'>
          确定
        </Button>
        <Button
          htmlType='button'
          onClick={onCancel}
          className='cancelBtn'
        >
          取消
        </Button>
      </Form.Item>
    </Form>
  );
}

export default AddFrom;
